<template>
	<view class="container" ref="bg">
		<!-- #ifdef MP-WEIXIN -->
		<!-- <tuicalling
		ref="TUICalling"
		id="TUICalling-component"
		:config="config">
	</tuicalling> -->
		<!-- #endif -->
		<view class="my_top_hight"></view>
		<!-- <fu-navbar title="" bgColor="#fff" >
			<view v-slot="center">
				<view class="text-center"  @click="$util.navTo('/pages/TUIKit/msginfo/msginfo?id='+conversationID)">{{conversationName}}</view>
			</view>
		</fu-navbar> -->
		<!-- <u-navbar
			title=""
			:autoBack="true"
		> -->
		 <view slot="center">
		 	<view class="text-center"  @click="conversation.type=='GROUP'?$util.navTo('/pages/TUIKit/msginfo/msginfo?id='+conversationID):''">{{conversationName||'没有找到相应的用户或群主'}}</view>
		 </view>
		<!-- </u-navbar> -->
		<!-- <view class="tui-chatroom-navigatorbar">
			<view class="conversation-title" @tap="navTo('/pages/chat_child/msginfo/msginfo?id='+conversationID)">{{ conversationName }}</view>
			<view class="right_icon">
				
			</view>
		</view> -->
		<!-- <view class="group-profile"><TUI-group-profile v-if="isShow" id="groip-profile" :conversation="conversation" /></view> -->
		<view class="message-list" @tap="triggerClose"><TUI-message-list id="message-list" ref="messageList" :conversation="conversation"  /></view>
		<view v-if="videoPlay" class="container-box" @tap.stop="stopVideoHander">
			<video
				v-if="videoPlay"
				class="video-message"
				:src="videoMessage.payload.videoUrl"
				:poster="videoMessage.payload.thumbUrl"
				object-fit="cover"
				error="videoError"
				autoplay="true"
				direction="0"
			/>
		</view>
		<view class="shopDetail flex align-center" v-if="show&&Detail!=null&&conversationName">
			<image class="image" :src="Detail?Detail.images[0]:''" mode="aspectFill" @click="previewImage"></image>
			<view class="right flex justify-between flex-column" >
				<view class="flex align-center justify-between" >
					<view class="title" @click="$util.navTo('/pages/commodity/commodity_details?id='+Detail.id)">{{Detail.goods_title}}</view>
					<u-icon name="close" color="#999" size="19" @click="show=false"></u-icon>
				</view>
				<view class="flex justify-between align-center" @click="$util.navTo('/pages/commodity/commodity_details?id='+Detail.id)">
					<view>
						<text class="text-sm text-orange">￥</text>
						<text class="text-xxl text-orange">{{Detail.price}}</text>
					</view>
					<view class="quyu text-666 text-sm">{{Detail.tid_text}}·{{Detail.system}}</view>
				</view>
			</view>
			
		</view>
		<view v-if="showChat" class="message-input" :style="{'bottom':height}">
			<TUI-message-input id="message-input" ref="messageInput" :conversation="conversation" @sendMessage="sendMessage" />
		</view>
	</view>
</template>

<script>
import logger from '@/common/logger';
import TUIMessageList from '../components/tui-chat/message-list/index';
import TUIMessageInput from '../components/tui-chat/message-input/index';
import TUIGroupProfile from '../components/tui-group/group-profile/index';
import TIM from '@/common/utils/tim';
const app = getApp();
export default {
	components: {
		TUIMessageList,
		TUIMessageInput,
		TUIGroupProfile
	},
	props: {},
	data() {
		return {
			conversationName: '',
			conversation: {},
			messageList: [],
			isShow: false,
			showChat: true,
			conversationID: '',
			videoPlay: false,
			videoMessage: {},
			authUrl:'',
			show:false,
			config: {
				sdkAppID: '',
				userID: '',
				userSig: '',
				type: 1,
				tim: null
			},
			height:'0px',
			Detail:null,
			isDarkMode: false, // 初始假设不是暗黑模式
		};
	},
	created() {
		uni.$on('videoPlayerHandler', value => {
			this.videoPlay = value.isPlay;
			this.videoMessage = value.message;
		});
		 
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// conversationID: C2C、 GROUP
		logger.log(` TUI-chat | onLoad | conversationID: ${options.conversationID}`);
		const { conversationID,shopid } = options;
		this.id=shopid
		if(this.id){//私聊
			this.shopid=shopid
		}else{//群聊
			this.shopid=this.extractNumbers(conversationID)[0]
		}
		this.conversationID=conversationID
		// #ifdef APP-PLUS 
		//  监听键盘高度变化
		uni.onKeyboardHeightChange((obj)=>{
		    // 获取系统信息
			let _sysInfo = uni.getSystemInfoSync();
			let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
			let _diff = obj.height - _heightDiff
			// 键盘高度
			this.height = (_diff > 0 ? _diff : 0) - 2 + "px";
			console.log(this.height)
		})
		// #endif
		TIM
			.setMessageRead({
				conversationID
			})
			.then(() => {
				logger.log('TUI-chat | setMessageRead  | ok');
			});
		// uni.$TUIKit.getConversationProfile(conversationID).then(res => {
		// 	// console.log(res.data);
		// 	const { conversation } = res.data;
		// 	this.conversation = conversation;
		// 	// this.setData({
		// 	// 	conversationName: this.getConversationName(conversation),
		// 	// 	isShow: conversation.type === 'GROUP'
		// 	// });
		// });
		// this.getCustomEmojis()
		// if(this.shopid){
		// 	this.getgameDetail()
		// }
		// this.checkDarkMode();
	},
	onShow() {
		TIM.getConversationProfile(this.conversationID).then(res => {
			console.log(res.data);
			const { conversation } = res.data;
			this.conversation = conversation;
			console.log('this.conversation',this.conversation)
			this.conversationName=this.getConversationName(conversation)
			console.log(this.conversationName)
			this.isShow=conversation.type === 'GROUP'
			
			// this.setData({
			// 	conversationName: this.getConversationName(conversation),
			// 	isShow: conversation.type === 'GROUP'
			// });
		});
		// this.getuserAuth()
	},
	mounted() {},
	onUnload() {
		
	},
	methods: {
		checkDarkMode() {
		  const systemInfo = uni.getSystemInfoSync();
		  console.log(systemInfo)
		  this.isDarkMode = systemInfo.osTheme || false;
		  console.log(this.isDarkMode)
		},
		extractNumbers(text) {
		    // 使用正则表达式匹配所有数字
		    const regex = /\d+/g;
		    // 使用match方法提取所有匹配的数字
		    return text.match(regex) ? text.match(regex).map(Number) : [];
		},
		previewImage(){
			uni.previewImage({
				urls:this.Detail.images
			})
		},
		getgameDetail(){
			this.$api.get(global.apiUrls.gamedetail,{
				id:this.shopid,
				type:this.id?'':1,
			}).then(res => {
			  this.Detail=res.data.data
			  // console.log(this.Detail)
			  this.show=true
			}).catch(err => {
			  
			})
		},
		// 法大大用户授权
		getuserAuth(){
			this.$api.get(global.apiUrls.userAuth,{
				user_id:global.userInfo.user_id,
			}).then(res => {
			  if(res.data.code==1){
				  console.log(res.data.data.authUrl)
				  this.authUrl=res.data.data.authUrl
			  }
			})
		},
		// 获取自定义表情包
		getCustomEmojis() {
		  // 替换为你的腾讯云账号的AppID和AppKey
		//   const appId = '1600031629';
		//   const appKey = 'a1521d17b87c4d17afb0b70ebb77cabfb55ca136983e4eef17dbd3612428a4c6';
		
		//   // 构造请求URL
		//   const url = `https://api.qcloud.com/v2/index.php?action=getCustomFace&access_token=${appId}%7C${appKey}`;
		
		//   // 发送请求
		//   wx.request({
		//     url: url,
		//     success: (res) => {
		//       console.log('自定义表情列表：', res.data);
		//       // 处理自定义表情列表数据
		//     },
		//     fail: (err) => {
		//       console.error('获取自定义表情列表失败：', err);
		//     },
		//   });
		},
		stopVideoHander() {
			this.videoPlay = false;
		},
		navTo(url){
			if(url.indexOf('GROUP')==-1){
				return;
			}
			this.$api.navTo(url);
		},
		getConversationName(conversation) {
			if (conversation.type === '@TIM#SYSTEM') {
				this.setData({
					showChat: false
				});
				return '系统通知';
			}

			if (conversation.type === 'C2C') {
				return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
			}

			if (conversation.type === 'GROUP'){
				console.log(conversation.groupProfile.name)
				return conversation.groupProfile.name || conversation.groupProfile.groupID;
			}
		},

		sendMessage(event) {
			// 将自己发送的消息写进消息列表里面
			this.$refs.messageList.updateMessageList(event.detail.message);
		},

		triggerClose() {
			if (this.showChat) {
				this.$refs.messageInput.handleClose();
			}
		},

		goBack() {
			const pages = getCurrentPages(); // 当前页面栈

			if (
				pages[pages.length - 2].route === 'pages/TUI-Conversation/create-conversation/create' ||
				pages[pages.length - 2].route === 'pages/TUI-Group/create-group/create' ||
				pages[pages.length - 2].route === 'pages/TUI-Group/join-group/join'
			) {
				uni.navigateBack({
					delta: 2
				});
			} else {
				uni.navigateBack({
					delta: 1
				});
			}

			TIM
				.setMessageRead({
					conversationID: this.conversationID
				})
				.then(() => {});
		}
	}
};
</script>
<style lang="less">
@import './chat.css';
.container{
	background-color: #fff;
}
</style>
